package top.jacktgq.sxt.bio.udp.demo8;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * @Author CandyWall
 * @Date 2019/10/21--9:59
 * @Description 发送端：使用面向对象封装
 */
public class TalkSend implements Runnable {

    private DatagramSocket client;
    private BufferedReader reader;
    private String toIp;
    private int toPort;

    public TalkSend(int port, String toIp, int toPort) {
        this.toIp = toIp;
        this.toPort = toPort;
        try {
            //1、使用DatagramSocket指定端口 创建发送端
            client = new DatagramSocket(port);
            //2、准备数据 键盘读取数据
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            String content = null;
            try {
                content = reader.readLine();
                byte[] data = content.getBytes();

                //3、封装成DatagramPacket 包裹，需要指定目的地
                DatagramPacket packet = new DatagramPacket(data, 0, data.length, new InetSocketAddress(toIp, toPort));

                //4、阻塞式接收包裹send(DatagramPacket p)
                client.send(packet);
                if (("bye".equals(content))) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //释放资源
        client.close();
    }
}
